package org.yhtch.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlEntityComplexChar {
	public static String decode(String encodedString) {
		String decodedString = new String(encodedString);

		String regexEntity = "&#\\d+;";
		String regexCodePoint = "\\d+";
		Pattern pEntity = Pattern.compile(regexEntity);
		Matcher mEntity = pEntity.matcher(encodedString);
		while (mEntity.find()) {
			// int findCount=mEntity.groupCount();
			// for(int i=0;i<=findCount;++i) {
			String strEntity = mEntity.group();
			Pattern pDigit = Pattern.compile(regexCodePoint);
			Matcher mDigit = pDigit.matcher(strEntity);
			if (mDigit.find()) {
				String strDigit = mDigit.group();
				String strPlain = new String(Character.toChars(Integer
						.parseInt(strDigit)));
				decodedString = decodedString.replace(strEntity, strPlain);
			}
			// }
		}

		return decodedString;
	}

	public static String encode(String decodedString) {
		String encodedString = "";
		int iCodePointCount = decodedString.codePointCount(0, decodedString
				.length());
		for (int index = 0; index < iCodePointCount; ++index) {
			int iCodePoint = decodedString.codePointAt(decodedString
					.offsetByCodePoints(0, index));
			encodedString += "&#" + iCodePoint + ";";
		}
		return encodedString;
	}

	public static void main(String[] args) {
		System.out.println(decode(encode("不管选择什么网页编码，网页都能正常显示")));
	}
}
